package com.project.poetry.common.aspect;

import com.project.poetry.common.constant.ConstantEnum;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.entity.R;
import com.project.poetry.common.exception.ServiceException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Objects;

/**
 * 异常监控
 * @author mengxj
 */
@RestControllerAdvice
public class HandleException {

    @ExceptionHandler(ServiceException.class)
    public R<String> handleServiceException(ServiceException e){
        Exception exception = e.getException();
        if(Objects.isNull(exception)){
            ConstantEnum constantEnum = e.getConstantEnum();
            if(Objects.isNull(constantEnum)){
                return R.fail(e.getMessage());
            }else{
                return R.fail(constantEnum);
            }
        }else {
            return this.handleException(exception);
        }
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
        ConstantEnum constantEnum = ConstantEnum.newConstant(ConstantValue.PARAM_ERROR_STATUS_CODE, Objects.requireNonNull(e.getBindingResult().getFieldError()).getDefaultMessage());
        return R.fail(constantEnum);
    }

    @ExceptionHandler(Exception.class)
    public R<String> handleException(Exception e){
        e.printStackTrace();
        return R.fail();
    }
}
